package day05;

import exception.DataAccessException;
import util.JdbcUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("*.product")
public class ProductServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String path=request.getServletPath();

        if("/list.product".equalsIgnoreCase(path)){
            list(request,response);
        }



    }

    protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ProductServlet.list()");


        List<Product> products=new ArrayList<Product>();

        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        try {
            con= JdbcUtil.getConnection();

            con.setAutoCommit(false);

            String sql=new StringBuffer()
                    .append("select * ")
                    .append("from t_product ")
                    .toString();

            ps=con.prepareStatement(sql);

            rs=ps.executeQuery();

            while (rs.next()){
                Product product=new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
                products.add(product);
            }

            con.commit();

        } catch (Exception e){
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
            throw new DataAccessException("数据访问失败",e);
        } finally {
            JdbcUtil.close(con,ps,rs);
        }

        request.setAttribute("products",products);

        request.getRequestDispatcher("/shop/list.jsp").forward(request,response);


    }

}
